package com.company.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Auther Xue
 * @Date 2021/4/15
 * @Version 1.0
 * @Desc    日期yyyy-MM-dd  与  Date 和 Calendar 互相转换
 */
public class StringDate {

    public static Calendar patternToDate(String str){
        if (str == null){
            throw new RuntimeException("请您传入参数");
        }
        String pattern = "yyyy-MM-dd";
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat s = new SimpleDateFormat(pattern);
        try {
            Date date = s.parse(str);
            calendar.setTime(date);
            return calendar;
        } catch (Exception e) {
            throw new RuntimeException("数据类型转换出现错误");
        }
    }
    public static Date patternToDateType(String str){
        if (str == null){
            throw new RuntimeException("请您传入参数");
        }
        String pattern = "yyyy-MM-dd";
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat s = new SimpleDateFormat(pattern);
        try {
            return s.parse(str);
        } catch (Exception e) {
            throw new RuntimeException("数据类型转换出现错误");
        }
    }
    public static Calendar patternToTime(String str){
        String pattern = "yyyy-MM-dd HH:mm:ss";
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat s = new SimpleDateFormat(pattern);
        try {
            Date date = s.parse(str);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calendar;
    }
    public static void dateToString(Calendar calendar){
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String date=sDateFormat.format(calendar.getTime());
        System.out.println(date);
    }
    public static void timeToString(Calendar calendar){
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date=sDateFormat.format(calendar.getTime());
        System.out.println(date);
    }
}
